﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Common.Util;
using ST.WX.Common;
using ST.WX.Common.Enums;
using ST.WX.Common.Model;
using ST.WX.MP.TplMsg.Model;
using System;
using System.Collections.Generic;

namespace ST.WX.MP.TplMsg
{
	/// <summary>
	/// 模板消息接口
	/// </summary>
	public class WXTplMsgApi
	{
		private readonly ILogger logger;
		private readonly WXBaseApi baseApi;

		public WXTplMsgApi(ILogger<WXTplMsgApi> _logger, WXBaseApi _baseApi)
		{
			logger = _logger;
			baseApi = _baseApi;
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="openID">接收者（用户）的 openid</param>
		/// <param name="tplID">所需下发的模板消息的id</param>
		/// <param name="url">URL置空，则在发送后，点击模版消息会进入一个空白页面（ios），或无法点击（android）</param>
		/// <param name="topColor">头部颜色</param>
		/// <param name="data">模板内容，不填则下发空模板</param>
		/// <returns></returns>
		public WXTplMsgSendResult Send(string appID, string appSecret, string openID, string tplID, string url, string topColor, string miniAppID, string miniPagePath, JObject data)
		{
			try
			{
				if (logger.IsEnabled(LogLevel.Debug))
				{
					logger.LogDebug("参数->appID:{0},openID:{1},tplID:{2},url:{3},topColor:{4},data:{5}",
						appID, openID, tplID, url, topColor, data);
				}

				var paras = new JObject {
					{ "touser", openID },
					{ "template_id", tplID },
					{ "url", url },
					{ "topcolor", topColor },
					{ "data", data }
				};
				if (!string.IsNullOrEmpty(miniAppID))
				{
					paras.Add("miniprogram", new JObject { { "appid", miniAppID }, { "page", miniPagePath } });
				}

				string respText = HttpHelper.Post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + baseApi.GetAccessToken(appID, appSecret), paras.ToString());
				if (string.IsNullOrEmpty(respText))
				{
					throw new WXException("发送模板消息失败，返回内容为空");
				}
				var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXTplMsgSendResult>(respText);
				if (ret.errcode != (int)WXErrorCode.请求成功)
				{
					throw new WXException(ret.errmsg);
				}
				return ret;
			}
			catch (WXException ex)
			{
				logger.LogError(ex, "发送模板消息出错");
				throw;
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "发送模板消息出错");
				throw new WXException("发送模板消息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="openID">接收者（用户）的 openid</param>
		/// <param name="tplID">所需下发的模板消息的id</param>
		/// <param name="url">URL置空，则在发送后，点击模版消息会进入一个空白页面（ios），或无法点击（android）</param>
		/// <param name="topColor">头部颜色</param>
		/// <param name="data">模板内容，不填则下发空模板</param>
		/// <returns></returns>
		public WXTplMsgSendResult Send(string appID, string appSecret, string openID, string tplID, string url, string topColor, string miniAppID, string miniPagePath, IEnumerable<WXTplMsgSendItem> data)
		{
			var paramData = new JObject { };
			if (data != null)
			{
				foreach (var p in data)
				{
					paramData.Add(p.name, new JObject { { "value", p.value }, { "color", p.color } });
				}
			}
			return Send(appID, appSecret, openID, tplID, url, topColor, miniAppID, miniPagePath, paramData);
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="openID">接收者（用户）的 openid</param>
		/// <param name="tplID">所需下发的模板消息的id</param>
		/// <param name="url">URL置空，则在发送后，点击模版消息会进入一个空白页面（ios），或无法点击（android）</param>
		/// <param name="topColor">头部颜色</param>
		/// <param name="data">模板内容，不填则下发空模板</param>
		/// <returns></returns>
		public WXTplMsgSendResult Send(string appID, string appSecret, string openID, string tplID, string url, string topColor, JObject data)
		{
			return Send(appID, appSecret, openID, tplID, url, topColor, null, null, data);
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="openID">接收者（用户）的 openid</param>
		/// <param name="tplID">所需下发的模板消息的id</param>
		/// <param name="url">URL置空，则在发送后，点击模版消息会进入一个空白页面（ios），或无法点击（android）</param>
		/// <param name="topColor">头部颜色</param>
		/// <param name="data">模板内容，不填则下发空模板</param>
		/// <returns></returns>
		public WXTplMsgSendResult Send(string appID, string appSecret, string openID, string tplID, string url, string topColor, IEnumerable<WXTplMsgSendItem> data)
		{
			var paramData = new JObject { };
			if (data != null)
			{
				foreach (var p in data)
				{
					paramData.Add(p.name, new JObject { { "value", p.value }, { "color", p.color } });
				}
			}
			return Send(appID, appSecret, openID, tplID, url, topColor, null, null, paramData);
		}

		/// <summary>
		/// 获得模板ID
		/// </summary>
		public WXTplMsgAddResult Add(string appID, string appSecret, string tplIDShort)
		{
			try
			{
				if (logger.IsEnabled(LogLevel.Debug))
				{
					logger.LogDebug("参数->appID:{0},tplIDShort:{1}",
						appID, tplIDShort);
				}

				var paras = new JObject {
					{ "template_id_short", tplIDShort },
				};

				string respText = HttpHelper.Post("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + baseApi.GetAccessToken(appID, appSecret), paras.ToString());
				if (string.IsNullOrEmpty(respText))
				{
					throw new WXException("获得模板ID失败，返回内容为空");
				}
				var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXTplMsgAddResult>(respText);
				if (ret.errcode != (int)WXErrorCode.请求成功)
				{
					throw new WXException(ret.errmsg);
				}
				return ret;
			}
			catch (WXException ex)
			{
				logger.LogError(ex, "获得模板ID出错");
				throw;
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "获得模板ID出错");
				throw new WXException("获得模板ID失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取模板列表
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="appSecret"></param>
		/// <returns></returns>
		public WXTplMsgListResult GetAll(string appID, string appSecret)
		{
			try
			{
				if (logger.IsEnabled(LogLevel.Debug))
				{
					logger.LogDebug("参数->appID:{0}",
						appID);
				}

				string respText = HttpHelper.Get("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + baseApi.GetAccessToken(appID, appSecret));
				if (string.IsNullOrEmpty(respText))
				{
					throw new WXException("获取模板列表失败，返回内容为空");
				}
				var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXTplMsgListResult>(respText);
				if (ret.errcode != (int)WXErrorCode.请求成功)
				{
					throw new WXException(ret.errmsg);
				}
				return ret;
			}
			catch (WXException ex)
			{
				logger.LogError(ex, "获取模板列表出错");
				throw;
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "获取模板列表出错");
				throw new WXException("获取模板列表失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}
	}
}
